package com.kagu.wms.manifest.httprov;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.kagu.wms.module.KaguModule;
import com.wowza.io.DirectRandomAccessReader;
import com.wowza.io.HTTPDirectRandomAccessReader;
import com.wowza.io.IRandomAccessReader;
import com.wowza.wms.application.IApplication;
import com.wowza.wms.application.IApplicationInstance;
import com.wowza.wms.http.HTTPServerVersion;
import com.wowza.wms.http.HTTProvider2Base;
import com.wowza.wms.http.IHTTPRequest;
import com.wowza.wms.http.IHTTPResponse;
import com.wowza.wms.httpstreamer.model.IHTTPStreamerSession;
import com.wowza.wms.logging.WMSLogger;
import com.wowza.wms.logging.WMSLoggerFactory;
import com.wowza.wms.module.ModuleBase;
import com.wowza.wms.module.ModuleConnect;
import com.wowza.wms.module.ModuleCore;
import com.wowza.wms.module.ModuleProperties;
import com.wowza.wms.server.IServer;
import com.wowza.wms.server.Server;
import com.wowza.wms.stream.MediaStreamBase;
import com.wowza.wms.util.ModuleUtils;
import com.wowza.wms.vhost.IVHost;
import com.wowza.wms.vhost.VHostSingleton;

public class AdobeManifestHTTProvider extends HTTProvider2Base {

	private StringBuilder content;
	private boolean isReadManifestFromFile;
	private String appName;
	private String appHostName;

	@Override
	public void init() {
		// TODO Auto-generated method stub
		super.init();
		isReadManifestFromFile = this.properties.getPropertyBoolean(
				"isReadManifestFromFiles", isReadManifestFromFile);
		
		
		
		System.err.println("http prov: " + isReadManifestFromFile);
		if (isReadManifestFromFile) {
			String homePath = VHostSingleton.getInstance(
					(String) VHostSingleton.getVHostNames().get(0))
					.getHomePath();

			System.err.println("home path: " + homePath);
			content = new StringBuilder();
			String sep = File.separator;
			try {
				BufferedReader br = new BufferedReader(new FileReader(homePath
						+ sep + "content" + sep + "am.f4m"));
				try {
					String line = null; // not declared within while loop
					while ((line = br.readLine()) != null) {
						content.append(line);
						content.append(System.getProperty("line.separator"));
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					try {
						br.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.err.println("##################################");
			System.err.println(content);
			System.err.println("##################################");
		} else {
			appName = this.properties.getPropertyStr("applicationName");
			appHostName = this.properties.getPropertyStr("applicationHostAddress");
			String retStr = "";
			// header
			retStr = (new StringBuilder(String.valueOf(retStr))).append(
					"<manifest xmlns=\"http://ns.adobe.com/f4m/2.0\">")
					.toString();

			retStr = (new StringBuilder(String.valueOf(retStr))).append(
					"<baseURL>http://"+appHostName+":1935/"+appName+"/</baseURL>").toString();
			//add video to the manifest file
			retStr = (new StringBuilder(String.valueOf(retStr)))
					.append("<media href=\"mp4:sample1_500kbps.f4v/manifest.f4m\" bitrate=\"500\"/>")
					.toString();
			
			//add audio to the manifest file
			Map<String, String> map = KaguModule.getTranslations();
			if((map != null)&&(!map.isEmpty())){
//			for(String name : map)	
//			retStr = (new StringBuilder(String.valueOf(retStr)))
//					.append("<media href=\"mp4:"+name+".f4v/manifest.f4m\" bitrate=\"40\" type=\"audio\" label=\"English\" lang=\"en\" alternate=\"true\"/>")
//					.toString();
			}
			retStr = (new StringBuilder(String.valueOf(retStr))).append(
					"</manifest>").toString();
		}
	}

	private void getSystem() {
		try {
			
			List<String> vhostNames = VHostSingleton.getVHostNames();
			// ret.append("<?xml version=\"1.0\"?>\n<WowzaMediaServer>");

			IServer server = Server.getInstance();

			// if (!isFlat)
			// {
			// outputConnectionInfo(ret, server.getConnectionCounter());
			// outputIOPerformanceInfo(ret, server.getIoPerformanceCounter());
			// }

			Iterator<String> iter = vhostNames.iterator();
			while (iter.hasNext()) {
				String vhostName = iter.next();
				IVHost vhost = (IVHost) VHostSingleton.getInstance(vhostName);
				if (vhost != null) {
					// if (!isFlat)
					// {
					// ret.append("<VHost>");
					// ret.append("<Name>"+URLEncoder.encode(vhostName,
					// "UTF-8")+"</Name>");
					// ret.append("<TimeRunning>"+vhost.getTimeRunningSeconds()+"</TimeRunning>");
					// ret.append("<ConnectionsLimit>"+vhost.getConnectionLimit()+"</ConnectionsLimit>");
					// outputConnectionInfo(ret, vhost.getConnectionCounter());
					// outputIOPerformanceInfo(ret,
					// vhost.getIoPerformanceCounter());
					// }

					List<String> appNames = vhost.getApplicationNames();
					Iterator<String> appNameIterator = appNames.iterator();
					while (appNameIterator.hasNext()) {
						String applicationName = appNameIterator.next();
						IApplication application = vhost
								.getApplication(applicationName);
						if (application == null)
							continue;

						// if (!isFlat)
						// {
						// ret.append("<Application>");
						// ret.append("<Name>"+URLEncoder.encode(applicationName,
						// "UTF-8")+"</Name>");
						// ret.append("<Status>loaded</Status>");
						// ret.append("<TimeRunning>"+application.getTimeRunningSeconds()+"</TimeRunning>");
						//
						// outputConnectionInfo(ret,
						// application.getConnectionCounter());
						// outputIOPerformanceInfo(ret,
						// application.getIoPerformanceCounter());
						// }
						//
						List<String> appInstances = application
								.getAppInstanceNames();
						Iterator<String> iterAppInstances = appInstances
								.iterator();
						while (iterAppInstances.hasNext()) {
							String appInstanceName = iterAppInstances.next();
							IApplicationInstance appInstance = application
									.getAppInstance(appInstanceName);
							if (appInstance == null)
								continue;

							// if (!isFlat)
							// {
							// ret.append("<ApplicationInstance>");
							// ret.append("<Name>"+URLEncoder.encode(appInstance.getName(),
							// "UTF-8")+"</Name>");
							// ret.append("<TimeRunning>"+appInstance.getTimeRunningSeconds()+"</TimeRunning>");
							//
							// outputConnectionInfo(ret,
							// appInstance.getConnectionCounter());
							// outputIOPerformanceInfo(ret,
							// appInstance.getIOPerformanceCounter());
							// }

							Map<String, Integer> flashCounts = appInstance
									.getPlayStreamCountsByName();
							Map<String, Integer> smoothCounts = appInstance
									.getHTTPStreamerSessionCountsByName(IHTTPStreamerSession.SESSIONPROTOCOL_SMOOTHSTREAMING);
							Map<String, Integer> cupertinoCounts = appInstance
									.getHTTPStreamerSessionCountsByName(IHTTPStreamerSession.SESSIONPROTOCOL_CUPERTINOSTREAMING);
							Map<String, Integer> sanjoseCounts = appInstance
									.getHTTPStreamerSessionCountsByName(IHTTPStreamerSession.SESSIONPROTOCOL_SANJOSESTREAMING);
							Map<String, Integer> rtspCounts = appInstance
									.getRTPSessionCountsByName();

							List<String> publishStreams = appInstance
									.getStreams().getPublishStreamNames();

							Set<String> streamNames = new HashSet<String>();
							streamNames.addAll(publishStreams);
							streamNames.addAll(flashCounts.keySet());
							streamNames.addAll(smoothCounts.keySet());
							streamNames.addAll(cupertinoCounts.keySet());
							streamNames.addAll(sanjoseCounts.keySet());
							streamNames.addAll(rtspCounts.keySet());

							Iterator<String> siter = streamNames.iterator();
						}
					}
				}
			}
		} catch (Exception e) {
			WMSLoggerFactory.getLogger(HTTPServerVersion.class).error(
					"HTTPServerInfoXML.onHTTPRequest: " + e.toString());
			e.printStackTrace();
		}
		// while(siter.hasNext())
		// {
		// String streamName = siter.next();
		// MyCounter counter = new MyCounter();
		//
		// if (isFlat)
		// {
		// int flashCount = toCount(flashCounts.get(streamName), counter);
		// int cupertinoCount = toCount(cupertinoCounts.get(streamName),
		// counter);
		// int smoothCount = toCount(smoothCounts.get(streamName), counter);
		// int sanjoseCount = toCount(sanjoseCounts.get(streamName), counter);
		// int rtspCount = toCount(rtspCounts.get(streamName), counter);
		//
		// ret.append("<Stream ");
		// ret.append("vhostName=\""+URLEncoder.encode(vhostName,
		// "UTF-8")+"\" ");
		// ret.append("applicationName=\""+URLEncoder.encode(applicationName,
		// "UTF-8")+"\" ");
		// ret.append("appInstanceName=\""+URLEncoder.encode(appInstanceName,
		// "UTF-8")+"\" ");
		// ret.append("streamName=\""+URLEncoder.encode(streamName,
		// "UTF-8")+"\" ");
		// ret.append("sessionsFlash=\""+flashCount+"\" ");
		// ret.append("sessionsCupertino=\""+cupertinoCount+"\" ");
		// ret.append("sessionsSanJose=\""+sanjoseCount+"\" ");
		// ret.append("sessionsSmooth=\""+smoothCount+"\" ");
		// ret.append("sessionsRTSP=\""+rtspCount+"\" ");
		// ret.append("sessionsTotal=\""+counter.total+"\" ");
		// ret.append("/>");
		// }
		// else
		// {
		// ret.append("<Stream>");
		// ret.append("<Name>"+URLEncoder.encode(streamName,
		// "UTF-8")+"</Name>");
		// ret.append("<SessionsFlash>"+toCount(flashCounts.get(streamName),
		// counter)+"</SessionsFlash>");
		// ret.append("<SessionsCupertino>"+toCount(cupertinoCounts.get(streamName),
		// counter)+"</SessionsCupertino>");
		// ret.append("<SessionsSanJose>"+toCount(sanjoseCounts.get(streamName),
		// counter)+"</SessionsSanJose>");
		// ret.append("<SessionsSmooth>"+toCount(smoothCounts.get(streamName),
		// counter)+"</SessionsSmooth>");
		// ret.append("<SessionsRTSP>"+toCount(rtspCounts.get(streamName),
		// counter)+"</SessionsRTSP>");
		// ret.append("<SessionsTotal>"+counter.total+"</SessionsTotal>");
		// ret.append("</Stream>");
		// }
		// }
	}

	public void onHTTPRequest(IVHost vhost, IHTTPRequest req, IHTTPResponse resp) {
		if (!doHTTPAuthentication(vhost, req, resp))
			return;
		// String retStr = "";
		// retStr = (new StringBuilder(String.valueOf(retStr))).append(
		// "<manifest xmlns=\"http://ns.adobe.com/f4m/2.0\">").toString();
		// retStr = (new StringBuilder(String.valueOf(retStr))).append(
		// "<baseURL>http://localhost:1935/vod/</baseURL>").toString();
		// retStr = (new StringBuilder(String.valueOf(retStr)))
		// .append(
		// "<media href=\"mp4:sample1_500kbps.f4v/manifest.f4m\" bitrate=\"500\"/>")
		// .toString();
		// retStr = (new StringBuilder(String.valueOf(retStr)))
		// .append(
		// "<media href=\"mp4:sample1_150kbps.f4v/manifest.f4m\" bitrate=\"150\"/>")
		// .toString();
		// retStr = (new StringBuilder(String.valueOf(retStr)))
		// .append(
		// "<media href=\"mp4:sample1_700kbps.f4v/manifest.f4m\" bitrate=\"700\"/>")
		// .toString();
		// retStr = (new StringBuilder(String.valueOf(retStr)))
		// .append(
		// "<media href=\"mp4:bigbuckbunny_1920.f4v/manifest.f4m\" bitrate=\"192\" type=\"audio\" label=\"Espanol\" lang=\"es\" alternate=\"true\"/>")
		// .toString();
		// retStr = (new StringBuilder(String.valueOf(retStr))).append(
		// "</manifest>").toString();

		System.err.println("!!!");
//		for (String name : KaguModule.getTranslationsList())
//			System.err.println("trans stream: " + name);
		try {
			resp.setHeader("Content-Type", "text/xml");
			OutputStream out = resp.getOutputStream();
			byte outBytes[] = content.toString().getBytes();
			out.write(outBytes);
		} catch (Exception e) {
			WMSLogger.getLogger("debug").error(
					"AdobeManifestHTTProvider: " + e.toString());
		}

	}

}
